Ext.onReady(function() {
    var psize_ztc = 18;
    var store_ztc;
    var jReader_ztc;
    var grid_ztc;
    var record_ztc;
    var subID0;
    var nodeid;
    var nodepar;
    var nodeparid;
    var tree_chaxun;
    var xg = Ext.grid; 
    var deep;
    var tree_root_cx = new Ext.tree.AsyncTreeNode( {
        text : '全部分类',
        id : '0'
    });
    
    var openUrl_ztc = basePath
    + 'JarpListener?className=cn.com.jsepc.rep.subject_pool.subject_poolGrid';
    openUrl_ztc += '&methodName=getsubpGrid&paramCount=5';   
    
    jReader_ztc = new Ext.data.JsonReader({
        root: 'data',
        totalProperty: 'totalCount',
        fields : [{
            name : 'subID'
        },{
            name : 'subCode'
        },{
            name:'subName'
        },{
            name:'subDesc'
        },{
            name:'subPID'
        },{
            name:'subLevel'
        }]
    });
		
 
    store_ztc = new Ext.data.Store({
        autoLoad:false,
        url:openUrl_ztc,
        reader : jReader_ztc,
        baseParams : {
            param_0 : 0,
            param_1 : psize_ztc,
            param_2:"",
            param_3:""
        }
    });
    store_ztc.setDefaultSort('subID', 'ASC');
	
    var sm = new xg.CheckboxSelectionModel({
        header:'',
        singleSelect : true,
        listeners: {
            selectionchange: function(sm) {
                if (sm.getCount()) {
                    var selections = grid_ztc.getSelectionModel().getSelections();
                    for(var i=0;i<selections.length;i++)
                    {
                        record_ztc=selections[i];
                    }                  
                    subID0=record_ztc.get("subID");
                } else {
                }
            }
        }  
        
    });
    var cm = new xg.ColumnModel( [ 
        sm,
        {
            id : 'subID',
            name :'subID',
            header  : '编号', 
            sortable : true, 
            dataIndex: 'subID',
            hidden:true
        },
        {
            name :'subCode',
            header  : '主题池编码', 
            sortable : true, 
            width:120,
            dataIndex: 'subCode'
        },
        {
            name :'subName',
            header : '主题池名称', 
            sortable : true, 
            dataIndex: 'subName'
        },
        {
            name :'subDesc',
            header : '主题池描述', 
            sortable : true, 
            dataIndex: 'subDesc'
        },
        {
            name :'subPID',
            header : '父级主题池ID', 
            sortable : true, 
            dataIndex: 'subPID',
            hidden:true
        },
        {
            name :'subLevel',
            header : '主题池层级', 
            sortable : true, 
            dataIndex: 'subLevel',
            hidden:true
        }
        ]);

    cm.defaultSortable = true;
    grid_ztc = new Ext.grid.GridPanel({
        id:'ztc',
        store:store_ztc,
        sm:sm,
        cm:cm, 
        anchor: '100% -82',
        deferredRender : false,
        activeTab : 0,  
        split: true,
        frame:true,
        viewConfig: {
            forceFit: true
        }, 
        enableColumnResize:true,//控制列大小调节
        enableColumnMove:true,//控制列的拖动
        loadMask:true,//数据加载时的遮罩功能 
        stripeRows: true, //显示行的分隔符
        columnLines:true,
        bbar: new Ext.PagingToolbar({
            store: store_ztc,
            paramNames : {
                start : 'param_0',
                limit : 'param_1'
            }, 
            emptyMsg : '没有数据需要显示',
            displayInfo: true,           
            pageSize: psize_ztc,
            listeners:{
                beforechange:function(bar,params){
                    bar.store.setBaseParam("param_2",Ext.ComponentMgr.get("KeyWord_bm").getValue());
                    bar.store.setBaseParam("param_3",Ext.ComponentMgr.get("KeyWord_mc").getValue());
                }
            }
        })
    });
    store_ztc.load();
		
    var toolbar_cha = new Ext.Toolbar( {
        stateful : true,
        items : [ new Ext.Toolbar.TextItem(), new Ext.Toolbar.SplitButton({
            text : '新增',
            handler : function() {
                if(nodeid==null || nodeid=="")
                {
                    Ext.Msg.alert('提示','请选择主题池分类！');
                }else{
                    if( nodeid==0){
                        Ext.Msg.alert('提示','此节点为根节点，不能新增同级！');
                    }else{
                        show_win_ztc();
                        Ext.getCmp("subPID").setValue(nodeparid);
                        Ext.getCmp("subLevel").setValue(deep);
                    }
                }
            },
            iconCls : 'blist',
            menu : {
                items : [ {
                    text : '同级分类',
                    handler : function() {
                        if(nodeid==null || nodeid==0){
                            Ext.Msg.alert('提示','此节点为根节点，不能新增同级！');
                        }else{
                            show_win_ztc();
                            Ext.getCmp("subPID").setValue(nodeparid); 
                            Ext.getCmp("subLevel").setValue(deep);
                        }                         
                    }
                }, {
                    text : '子级分类',
                    handler : function() {
                        show_win_ztc();
                        Ext.getCmp("subPID").setValue(nodeid);
                        Ext.getCmp("subLevel").setValue(deep);
                    }
                } ]
            }
        }),'-',{
            text:'编辑',
            handler : function(){
                var checkse= Ext.ComponentMgr.get("ztc").getSelectionModel().getSelected();
                if(checkse == null  || checkse == "")
                {
                    Ext.Msg.alert('提示','请勾选需要编辑的主题池！');
                }else{
                    show_win_ztc();
                    Ext.getCmp("subID").setValue(record_ztc.get("subID"));
                    Ext.getCmp("subCode").setValue(record_ztc.get("subCode"));
                    Ext.getCmp("subName").setValue(record_ztc.get("subName"));
                    Ext.getCmp("subDesc").setValue(record_ztc.get("subDesc"));
                    Ext.getCmp("subPID").setValue(record_ztc.get("subPID"));
                    Ext.getCmp("subLevel").setValue(record_ztc.get("subLevel"));
                }
            }
        },'-',{
            text:'删除',
            handler : function(){
                var checkse= Ext.ComponentMgr.get("ztc").getSelectionModel().getSelected();
                if(checkse == null  || checkse == "")
                {
                    Ext.Msg.alert('提示','请勾选需要删除的主题池！');
                }else{
                    deleteFrom_ztc();
                }
            }
        },'-',{
            text:'关联指标',
            handler : function(){
                show_win_ztcrep(); 
            }
        },'-',{
            xtype:"hidden",
            id:'get_p_id'
        }]
    });
    
    //左侧树
    tree_chaxun = new Ext.tree.TreePanel(
    {
        //renderTo : 'tree_chaxun',
        border : '0',
        //height : 900,
        height : '100%',
		anchor : '100% 100%',
        width : 200,
        useArrows : true, // 使用箭头
        autoScroll : true,
        animate : true, // 动画
        enableDD : false, // 可拖动
        containerScroll : true,
        rootVisible : true,
        root : tree_root_cx,
        listeners : {
            beforeload : function(node) {
                var openUrl = basePath + 'JarpListener?className=cn.com.jsepc.rep.subject_pool.GetTree&methodName=GetData&paramCount=1&param_0='+node.id
                node.loader = new Ext.tree.TreeLoader( {
                    dataUrl : openUrl
                });
            }
        }
    });

    var viewport = new Ext.Viewport( {
        layout : 'border',
        items : [ {
            region : 'center',
            layout : 'border',
            tbar : toolbar_cha,
            items : [ {
                tools : [ {
                    id : 'refresh',
                    handler : function() {
                        if (tree_root_cx != null) {
                            tree_root_cx.reload();
                        }
			
                    }
                } ],
                title:'主题池分类',
                split:true,
                collapsible : true,
                region : 'west',
                layout:'anchor',
                autoScroll : true,
                width : 200,
                items:[tree_chaxun]
               // html : '<div id="tree_chaxun"></div>'
            }, 
            new Ext.Panel( {
                region : 'center',
                layout:"anchor",
                frame : true,
                title : '主题池列表',
                deferredRender : false,
                activeTab : 0, 
                items:[
                    new Ext.FormPanel({
                    anchor: '-0,-0',
                    layout : 'form',
                    labelWidth : 80,
                    width : '98%',
                    height: '100%',
                    bodyStyle : 'padding: 0 10px 0 10px',
                    border : false,
                    items : [ {
                        title : '查询条件',
                        layout : 'form',
                        xtype : 'fieldset',
                        bodyStyle : 'padding: 0 0 0 50px',
                        collapsible : true,
                        collapsed : false,
                        labelAlign : 'right',
                        height : '100%',
                        defaults : {
                            width : '100%'
                        },
                        items : [
                        {
                            layout : 'column',
                            border : false,
                            items : [ {
                                columnWidth : .3,
                                layout : 'form',
                                labelWidth : 80,
                                border : false,
                                bodyStyle : 'padding:5px 5px 0',
                                items : [
                                {
                                    xtype : "textfield",
                                    fieldLabel : '主题池编码',
                                    emptyText : '请输入',
                                    width : '100%',
                                    id : 'KeyWord_bm'
                                } ]
                            },{
                                columnWidth : .35,
                                layout : 'form',
                                labelWidth : 80,
                                border : false,
                                bodyStyle : 'padding:5px 5px 0',
                                items : [
                                {
                                    xtype : "textfield",
                                    fieldLabel : '主题池名称',
                                    emptyText : '请输入',
                                    width : '100%',
                                    id : 'KeyWord_mc'
                                } ]
                            },
                            {
                                columnWidth : .3,
                                layout : 'form',
                                labelWidth : 80,
                                anchor : '100%',
                                border : false,
                                bodyStyle : 'padding:5px 0 5px 30px',
                                items : [{
                                    xtype : "button",
                                    id : 'query_tbar',
                                    text : "查    询",
                                    width : 60,
                                    handler : function() {
                                        selectItem_ztc();
                                    }
                                } ]
                            }
                            ]
                        } 
                        ]
                    } ]	    	
                }),grid_ztc]
            })]
        } ]
    });
		
   
		
    tree_chaxun.on('click',function(node) {
        if (node){
            nodeid = node.id;
            deep = node.getDepth();
            if(nodeid!=0){
                nodepar=node.parentNode;
                nodeparid=nodepar.id;
            }
        }
        if(node.isLeaf()==true){
            var openUrl = basePath
            + 'JarpListener?className=cn.com.jsepc.rep.subject_pool.subject_poolGrid';
            openUrl += '&methodName=getSubId&paramCount=1&param_0='+node.id;  
            store_ztc.proxy=new Ext.data.HttpProxy({
                url:openUrl
            });
            store_ztc.load();
        }else{
            store_ztc.proxy=new Ext.data.HttpProxy({
                url:openUrl_ztc
            });
            store_ztc.load({
                params : {
                    param_2:Ext.ComponentMgr.get("KeyWord_bm").getValue(),
                    param_3:Ext.ComponentMgr.get("KeyWord_mc").getValue(),
                    param_4:nodeid
                }
            });	
            setempty();	
        }
        		
    });
				
    function selectItem_ztc() {	
        var KeyWord_bm=Ext.ComponentMgr.get("KeyWord_bm").getValue();
        var KeyWord_mc=Ext.ComponentMgr.get("KeyWord_mc").getValue();
        store_ztc.load({
            params : {
                param_2:KeyWord_bm,
                param_3:KeyWord_mc,
                param_4:nodeid
                
            }
        });
    }
		
    function setempty() {
        Ext.ComponentMgr.get("KeyWord_bm").setValue("");
        Ext.ComponentMgr.get("KeyWord_mc").setValue("");
    };
    
    
    //删除
    function  deleteFrom_ztc() {
        Ext.MessageBox.show({
            title:'提示框',
            msg: ' 确定删除吗',                
            buttons:{
                'yes':'确定',
                'no': '取消'
            },
            fn: showResult1,
            icon: Ext.MessageBox.QUESTION
        });
        function showResult1(btn){
            if(btn == 'yes'){ 
                var saveItemInfoUrl = "";
                saveItemInfoUrl = '?className=cn.com.jsepc.rep.subject_pool.subject_poolGrid';
                saveItemInfoUrl += '&methodName=subject_poolDelete';
                saveItemInfoUrl += '&paramCount=1'+'&param_0='+subID0;

                saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
                httpR_itemInfo = getXMLHttpRequest();
                httpR_itemInfo.onreadystatechange = returnItemDelete;
                httpR_itemInfo.open("POST", saveItemInfoUrl, true);
                httpR_itemInfo.send();
            }else if( btn == 'no')
            {
                return;
            }
        }       
    }
    function returnItemDelete() {
        if (httpR_itemInfo.readyState == 4) {
            if (httpR_itemInfo.status == 200) {
                var ret = httpR_itemInfo.responseText;
                if (ret=='true'){
                    Ext.Msg.alert('提示','删除成功！');
                    refresh();
                    grid_ztc.store.reload();
                }else if(ret=='false'){
                    Ext.Msg.alert('提示','删除失败！');
                }else if(ret=='haverep'){
                    Ext.Msg.alert('提示','该主题池有关联指标，不能删除！');
                }else if(ret=='havesub'){
                    Ext.Msg.alert('提示','该主题池有子级主题，不能删除！');
                }
            }
        }
    }
    
    //弹出的面板
    function show_win_ztc(win_ztc){
        var fsf = new Ext.FormPanel({          
            labelWidth: 130,
            region: 'center',
            frame:true,
            bodyStyle:'padding:10px 10px 0',
            width: 430,
            height:300, 
            defaults: {
                width: 210
            },
            defaultType: 'textfield',
            items :[
            {         
                xtype : 'hidden',
                id: 'subID',
                fieldLabel: '编号',
                name: 'subID'              
            },
            {
                id: 'subCode',
                fieldLabel: '主题池编码',
                name: 'subCode',
                blankText:'此项必填',
                allowBlank : false,
                emptyText : '请输入唯一的主题池编码',
                regex :/^[A-Za-z0-9_]+$/,  
                regexText : '您输入的字符串只能由中文，英文字母，数字和下划线组成！',
                maxLength: 32               
            },{
                id: 'subName',
                fieldLabel: '主题池名称',
                name: 'subName',
                blankText:'此项必填',
                allowBlank : false,
                emptyText : '请输入唯一的主题池名称',
                regex:/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/,
                maxLength: 32
            },{
                id: 'subDesc',
                fieldLabel: '主题池描述',
                name: 'subDesc',
                emptyText : '可选填',
                maxLength: 90,
                height:70
            },{
                xtype : 'hidden',
                id: 'subPID',
                fieldLabel: '父级主题池ID',
                name: 'subPID',
                blankText:'此项必填',
                allowBlank : false,
                emptyText : '请输入父级主题池ID',
                maxLength: 32               
            },{
                xtype : 'hidden',
                id: 'subLevel',
                fieldLabel: '主题池层级',
                name: 'subLevel',
                blankText:'此项必填',
                allowBlank : false,
                emptyText : '请输入主题池层级',
                maxLength: 32               
            }
            ]
        });
        
        win_ztc = new Ext.Window({   
            title: '主题池信息',  
            closable:true,
            width:430,
            height:300,
            plain:true,
            modal:true,
            layout: 'border',         
            items: [fsf],
            tbar : ['-', 
            {
                text:'保存',
                handler : function(){
                    saveForm();
                }
            },'-', {
                text:'关闭',
                handler : function(){
                    win_ztc.close();
                }
            }         
            ]
	             
        });         
        win_ztc.show();

        formStore_ztc = new Ext.data.Store(['subID', 'subCode','subName','subDesc','subPID','subLevel']); 
       
        //保存
        function saveForm() {
            if (gvalue()){ 	
                var subID=Ext.ComponentMgr.get("subID").getValue();
                if( subID == ""){                  	       
                    var saveItemInfoUrl = "";
                    saveItemInfoUrl = '?className=cn.com.jsepc.rep.subject_pool.subject_poolGrid';
                    saveItemInfoUrl += '&methodName=subject_poolAdd';
                    saveItemInfoUrl += '&paramCount=0';
	
                    saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
                    httpR_itemInfo = getXMLHttpRequest();
                    httpR_itemInfo.onreadystatechange = returnItemAdd;
                    httpR_itemInfo.open("POST", saveItemInfoUrl, true);
                    httpR_itemInfo.send(Ext.util.JSON.encode(formStore_ztc));
	            
                }else if( subID != ""){                
                    var saveItemInfoUrl = "";
                    saveItemInfoUrl = '?className=cn.com.jsepc.rep.subject_pool.subject_poolGrid';
                    saveItemInfoUrl += '&methodName=subject_poolUpdate';
                    saveItemInfoUrl += '&paramCount=0';
	
                    saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
                    httpR_itemInfo = getXMLHttpRequest();
                    httpR_itemInfo.onreadystatechange = returnItemUpdate;
                    httpR_itemInfo.open("POST", saveItemInfoUrl, true);
                    httpR_itemInfo.send(Ext.util.JSON.encode(formStore_ztc));
                }
            }
        }
        function returnItemAdd() {
            if (httpR_itemInfo.readyState == 4) {
                if (httpR_itemInfo.status == 200) {
                    var res = httpR_itemInfo.responseText;
                    if (res=="true"){
                        Ext.MessageBox.show({
                            title:'提示框',
                            msg: ' 保存成功 ',                
                            buttons:{
                                'yes':'确定'
                            },
                            fn: showResult3
                        });
                        function showResult3(btn){
                            if(btn=="yes"){
                                Ext.ComponentMgr.get("subID").setValue("");
                                Ext.ComponentMgr.get("subCode").setValue("");
                                Ext.ComponentMgr.get("subName").setValue("");
                                Ext.ComponentMgr.get("subDesc").setValue("");      
                                Ext.ComponentMgr.get("subPID").setValue("");   
                                Ext.ComponentMgr.get("subLevel").setValue("");   
                            }
                            win_ztc.close();
                        }
                        refresh();
                        grid_ztc.store.reload();
                    }else if(res=='false'){
                        Ext.Msg.alert('提示','保存失败,主题池编码或主题池名称出现重复！');
                    }else if(res=='error'){
                        Ext.MessageBox.show({
                            title:"提示",
                            msg:"保存失败!",
                            buttons:{
                                'yes':'确定'
                            },
                            fn: showResult
                        });
                        function showResult(btn){
                            if(btn=="yes"){
                                win_ztc.close();
                            }
                        }
                    }
                }
            }
        }
    
    
    
        function returnItemUpdate() {
            if (httpR_itemInfo.readyState == 4) {
                if (httpR_itemInfo.status == 200) {
                    var res = httpR_itemInfo.responseText;
                    if (res=="true"){
                        Ext.MessageBox.show({
                            title:'提示框',
                            msg: ' 保存成功 ',                
                            buttons:{
                                'yes':'确定'
                            },
                            fn: showResult4
                        });
                        function showResult4(btn){
                            if(btn=="yes"){
                                Ext.ComponentMgr.get("subID").setValue("");
                                Ext.ComponentMgr.get("subCode").setValue("");
                                Ext.ComponentMgr.get("subName").setValue("");
                                Ext.ComponentMgr.get("subDesc").setValue("");
                                Ext.ComponentMgr.get("subPID").setValue("");   
                                Ext.ComponentMgr.get("subLevel").setValue("");   
                                win_ztc.close();
                                refresh();
                                grid_ztc.store.reload();                       
                            }
                        }
                    }else if(res=='false'){
                        Ext.Msg.alert('提示','保存失败,主题池编码或主题池名称出现重复！');
                    }else if(res=='error'){
                        Ext.MessageBox.show({
                            title:"提示",
                            msg:"保存失败!",
                            buttons:{
                                'yes':'确定'
                            },
                            fn: showResult5
                        });
                        function showResult5(btn){
                            if(btn=="yes"){
                                win_ztc.close();
                            }
                        }
                    }
                }
            }
        }
    
        function gvalue(){
            var subID=Ext.ComponentMgr.get("subID").getValue();
            var subCode=Ext.ComponentMgr.get("subCode").getValue();
            var subName=Ext.ComponentMgr.get("subName").getValue();
            var subDesc=Ext.ComponentMgr.get("subDesc").getValue();
            var subPID=Ext.ComponentMgr.get("subPID").getValue();   
            var subLevel=Ext.ComponentMgr.get("subLevel").getValue();   
        
            if( subCode == null  || subCode == ""){
                Ext.Msg.alert('提示','主题池编码不能为空！');
                return false;
            }else if(isDigit(subCode) ){
                Ext.Msg.alert('提示','主题池编码中不能包含单双引号等特殊符号！');
                return false;
            }else if(isDigitzh(subCode) ){
                Ext.Msg.alert('提示','主题池编码不能以数字或下划线开头,只能是字母开头！');
                return false;
            } 
               
            else if(subName == null  || subName == ""){
                Ext.Msg.alert('提示','主题池名称不能为空！');
                return false;
            }else if(isDigit(subName) ){
                Ext.Msg.alert('提示','主题池名称中不能包含单双引号等特殊符号！');
                return false;
            }
                 
            else{       
                formStore_ztc.subID = subID;
                formStore_ztc.subCode = subCode;
                formStore_ztc.subName = subName;
                formStore_ztc.subDesc = subDesc;
                formStore_ztc.subPID = subPID;
                formStore_ztc.subLevel = subLevel;
                return true;
            }		 
        }
        
        //判断字符串中不包含特殊字符
        function isDigit(s) 
        { 
            var patrn=/^[^ '":();!,.=+{}\-?\\@#$%^&*~\s]*$/; 
            if (patrn.exec(s)){
                return false; 
            }else{
                return true;
            }
        }

        
        //判断字符串不能以数字开头
        function isDigitzh(s) 
        { 
            var patrn=/^[a-zA-Z][a-zA-Z0-9_]{0,32}$/; 
            if (patrn.exec(s)){
                return false; 
            }else{
                return true;
            }
        }       
     
    }     
    
       function refresh(){      
            var node = tree_chaxun.getSelectionModel().getSelectedNode();
            if(node == null) {
                tree_chaxun.root.reload();
            }else{
    			if(node.isLeaf()==true){
			    	nodepar = node.parentNode;
					var path = nodepar.getPath('id');
					tree_chaxun.root.reload();
					tree_chaxun.selectPath(path, "id");
				}else{
                	var path = node.getPath('id'); 
                	tree_chaxun.root.reload();
                	tree_chaxun.selectPath(path,"id");
                }
            }
        }
        
});